package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southwind.common.ResultObj;
import com.southwind.common.UserPageModel;
import com.southwind.entity.AfterSalesMessage;
import com.southwind.entity.User;
import com.southwind.mapper.CarMapper;
import com.southwind.service.UserService;
import com.southwind.vo.AfterSalesVO;
import com.southwind.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CarMapper carMapper;

    @PostMapping("/add")
    public ResultObj add(@RequestBody User user){
        boolean save = this.userService.save(user);
        if(save) return ResultObj.USER_ADD_SUCCESS;
        return ResultObj.USER_ADD_ERROR;
    }

    @PostMapping("/update")
    public ResultObj update(@RequestBody User user){
        boolean save = this.userService.updateById(user);
        if(save) return ResultObj.USER_UPDATE_SUCCESS;
        return ResultObj.USER_UPDATE_ERROR;
    }

    @DeleteMapping("/delete/{id}")
    public ResultObj delete(@PathVariable("id") Integer id){
        boolean removeById = this.userService.removeById(id);
        if(removeById) return ResultObj.USER_DELETE_SUCCESS;
        return ResultObj.USER_DELETE_ERROR;
    }

    @GetMapping("/list")
    public Map list(UserPageModel userPageModel){
        Page<User> page = new Page<>(userPageModel.getPage(), userPageModel.getLimit());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(userPageModel.getUsername()), "username", userPageModel.getUsername());
        Page<User> resultPage = this.userService.page(page, queryWrapper);
        Map map = new HashMap();
        map.put("count", resultPage.getTotal());
        List<UserVO> list = new ArrayList<>();
        for (User record : resultPage.getRecords()) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(record, userVO);
            userVO.setCarNumber(this.carMapper.getCarNumberById(record.getCid()));
            list.add(userVO);
        }
        map.put("data", list);
        return map;
    }

    @GetMapping("/car")
    public List<User> car(){
        return this.userService.list();
    }
}

